import java.util.concurrent.ConcurrentHashMap;


public class demo5 {
    public static void main(String[] args) {
        // 创建一个 ConcurrentHashMap
        ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();

        // 添加键值对
        map.put("Apple", 1);
        map.put("Banana", 2);
        map.put("Orange", 3);

        // 并发读取
        Runnable readTask = () -> {
            for (String key : map.keySet()) {
                System.out.println(key + ": " + map.get(key));
            }
        };

        // 并发写入
        Runnable writeTask = () -> {
            map.put("Grapes", 4);
            map.put("Mango", 5);
        };

        // 启动多个线程进行读写操作
        Thread reader1 = new Thread(readTask);
        Thread reader2 = new Thread(readTask);
        Thread writer1 = new Thread(writeTask);
        Thread writer2 = new Thread(writeTask);

        reader1.start();
        reader2.start();
        writer1.start();
        writer2.start();

        try {
            reader1.join();
            reader2.join();
            writer1.join();
            writer2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        // 输出结果
        System.out.println("Final map: " + map);
    }

}
